package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.entity.Employee;
import com.itheima.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * @author Tang
 * @date 2023/4/11
 */
@RequestMapping("/employee")
@RestController
@Slf4j
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    //controller-->service-->dao

    /**
     * 员工登录
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session){
        //1、将页面提交的密码password进行md5加密处理
        String username = employee.getUsername();
        String password = employee.getPassword();       //接收前端传递过来的明文密码
        if(password == null || username == null) {
            return R.error("请输入用户名或密码！");
        }
        String pwd = DigestUtils.md5DigestAsHex(password.getBytes());  //加密后的密码

        //2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername, username);
        Employee emp = employeeService.getOne(wrapper);

        //3、如果没有查询到则返回登录失败结果
        if (emp == null) {
            return R.error("该用户名不存在！");
        }

        //4、密码比对，如果不一致则返回登录失败结果
        if (!emp.getPassword().equals(pwd)) {
            return R.error("用户名密码不匹配！");
        }

        //5、查看员工状态，如果为已禁用状态，则返回员工已禁用结果 0代表禁用  1代表正常
        if (emp.getStatus() == 0) {
            return R.error("该用户已被禁用！");
        }

        //6、登录成功，将员工id存入Session并返回登录成功结果
        session.setAttribute("employee", emp.getId());
        return R.success(emp);
    }

    /**
     * 员工退出
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpSession session){
        //1.清理session中的员工id
        session.invalidate();

        //2.返回结果
        return R.success("退出成功！");
    }

    /**
     * 新增员工
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> add(@RequestBody Employee employee, HttpSession session){
        //1.接收前端请求，调用service新增方法
        boolean flag = employeeService.addEmp(employee, session);
        //2.返回结果
        return flag ? R.success("新增员工成功！") : R.error("新增员工失败！");
    }

    /**
     * 员工分页
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<Employee>> page(@RequestParam(defaultValue = "1") Integer page,
                                  @RequestParam(defaultValue = "10") Integer pageSize, String name){
        //1. 获取前端参数，调用service的分页查询
        Page<Employee> pageInfo = employeeService.findPage(page, pageSize, name);
        //2. 直接返回分页结果
        return R.success(pageInfo);
    }

    /**
     * 员工启用|禁用、编辑员工
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Employee employee, HttpSession session){
        log.info("EmployeeController:当前线程id={}",Thread.currentThread().getId());
        //1.补充字段更新时间和更新人
        //优化：使用MP公共字段自动填充功能
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser((Long) session.getAttribute("employeeId"));

        //2.调用service的更新方法
        boolean flag = employeeService.updateById(employee);

        //3.返回结果
        return flag ? R.success("状态更新成功！") : R.error("状态更新失败！");
    }

    /**
     * 回显员工信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getEmp(@PathVariable Long id){
        //1.调用service的查询方法（根据id查询）
        Employee employee = employeeService.getById(id);
        //2.返回结果
        return R.success(employee);
    }
}
